package com.itheima.wed.servlet;

import com.itheima.domain.User;
import com.itheima.servicce.UserService;
import com.itheima.servicce.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/addUserServlet")
public class AddUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //1. 设置请求编码
            request.setCharacterEncoding("utf-8");
            //2. 获取请求所有参数
            Map<String, String[]> map = request.getParameterMap();
            //3. 封装到User对象中
            User users =new User();
            BeanUtils.populate(users,map);
            //4. 调用service保存
            UserService service = new UserServiceImpl();
            service.save(users);
            //5. 重定向到userListServlet,再次查询
            response.sendRedirect(request.getContextPath()+"/userListServlet");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } finally {
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}